package com.fpx.order.plat.bussiness.plat.amazon.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fpx.api.bean.order.Order;
import com.fpx.api.bean.order.OrderItem;
import com.fpx.api.bean.request.SubmitOrderRequest;
import com.fpx.api.bean.response.ResultMessage;
import com.fpx.api.bean.response.SubmitOrderResponse;
import com.fpx.api.service.IAmazonService;
import com.fpx.api.util.Constant;
import com.fpx.order.plat.bussiness.cache.CacheManage;
import com.fpx.order.plat.bussiness.entity.CustomerShop;
import com.fpx.order.plat.bussiness.entity.OriginOrder;
import com.fpx.order.plat.bussiness.entity.OriginOrderitem;
import com.fpx.order.plat.bussiness.plat.base.IPlatDeliveryOrderHandler;
import com.fpx.order.plat.bussiness.plat.base.SdkCommonOrderDeliverThread;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderService;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderitemService;
import com.fpx.order.plat.bussiness.system.CacheConstants;
import com.fpx.order.plat.bussiness.system.PlatConstants;
/**
 * 订单回传服务类
 * desc: AmazonDeliveryOrderHandler
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年12月8日 下午1:50:29
 * @version 1.0
 */
@Component
public class AmazonDeliveryOrderHandler implements IPlatDeliveryOrderHandler{
	
	private final static Logger LOGGER = Logger.getLogger(AmazonDeliveryOrderHandler.class);
	
	@Autowired
	private IOriginOrderService originOrderService;
	
	@Autowired
	private IOriginOrderitemService originOrderitemService;
	
	@Autowired
	private IAmazonService amazonService;
	
	@Autowired 
	private CacheManage cacheManage;
	
	@Override
	public void deliveryOrder(CustomerShop customer,int reqNum) throws Exception {
		//客户编号
		String cm_id = customer.getCm_id();
		//店铺代码
		String cs_code = customer.getCs_code();
		//获取店铺TOKEN
		String token = customer.getCs_token();
				
		SubmitOrderRequest request = new SubmitOrderRequest();
		
		Map<String,String>configMap=
				cacheManage.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_AMAZON);
		request.setConfigMap(configMap);
		
		//亚马逊平台的授权令牌
		request.setToken(token);
		//平台类型   AMAZON
		request.setPlatform(Constant.PLATFORM_AMAZON);
		//站点
		request.setSite(customer.getCs_site());
		//封装订单信息
		List<Order> orders = new ArrayList<Order>();
		//需要同步的订单集合
		List<OriginOrder> orderList = originOrderService.findDeliveryOrder(cm_id, cs_code, PlatConstants.ORDER_SOURCE_AM);
		if(null == orderList || orderList.size() <= 0){
			LOGGER.info("卖家【" + cm_id + "】的【"+cs_code+"】店铺没有需要同步的订单");
			return;
		}
	
		for (int j = 0; j < orderList.size(); j++) {
			OriginOrder originOrder = orderList.get(j);
			if(originOrder==null){
				continue;
			}
			if(StringUtils.isEmpty(originOrder.getOrder_code())||
					StringUtils.isEmpty(originOrder.getShip_server_code())){
				continue;
			}
			Order order = new Order();
			//客户单证号
			order.setOrderNo(originOrder.getOrder_code());
			//跟踪单号（运单号）
			order.setTrackingNo(originOrder.getShip_server_code());
			//运输方式（承运商）
			if(StringUtils.isEmpty(originOrder.getShipping_service())){
				order.setShipway4px("Other");
			}else{
				order.setShipway4px(originOrder.getShipping_service());
			}
			//根据订单主键查询订单货品信息
			List<OriginOrderitem> detilList = originOrderitemService.findByPfooId(originOrder.getPfoo_id());
			List<OrderItem> items = new ArrayList<OrderItem>();
			for (int k = 0; k < detilList.size(); k++) {
				OriginOrderitem orderitem = detilList.get(k);
				OrderItem itemInfo = new OrderItem();
				String itemId = orderitem.getItem_id();
				if(StringUtils.isEmpty(itemId)){
					continue;
				}
				//物品ID
				itemInfo.setItemId(orderitem.getItem_id());
				//物品数量
				itemInfo.setQuantity(Integer.parseInt(orderitem.getQuantity()));
				items.add(itemInfo);
			}
			order.setItems(items);
			orders.add(order);
			if((j!=0&&j%20==0)||j==(orderList.size()-1)){
				List<Order> cloneOrderList = new ArrayList<Order>();
				cloneOrderList.addAll(orders);
				request.setOrders(cloneOrderList);
				//控制调用次数,amazon 限制了1小时最多只能调用30次
				reqNum++;
				if(reqNum>30){
					break;
				}
				//获取返回结果
				SdkCommonOrderDeliverThread requestThread = new SdkCommonOrderDeliverThread(orders.size()
						,request,PlatConstants.ORDER_SOURCE_AM,amazonService);
				new Thread(requestThread).start();
				SubmitOrderResponse response = requestThread.getResponse();
				if(response == null){
					LOGGER.error("-----------------结束同步Amazon店铺：【" + cs_code + "】已发货的销售接口表订单,请求超时.------------------------------");
					continue;
				}
				//结果状态码   Constant.ACK_SUCCESS 和 Constant.ACK_FAIL
				String ack = response.getAck();
				if(ack.equals(Constant.ACK_SUCCESS)){
					String feedSubmitId = response.getAmazonSubmitResultId();
					//同步成功更新销售接口表同步状态
					if(StringUtils.isNotEmpty(feedSubmitId)){
						//封装订单列表
		            	List<String> orderIds = new ArrayList<String>();
		            	for(Order reqOrder:request.getOrder()){
		            		orderIds.add(reqOrder.getOrderNo());
		            	}
		            	originOrderService.updateDeliveryStatusSuccess(orderIds, PlatConstants.ORDER_SOURCE_AM);
					}
				}else{
					String  failMessage = response.getFailMessage();
					LOGGER.error(failMessage);
					List<ResultMessage> detailMessages = response.getDetailMessages();
					if(detailMessages==null||detailMessages.size()<=0){
						continue;
					}
					for(ResultMessage detailMessage : detailMessages){
						//订单id
						LOGGER.error("同步亚马逊订单发货异常：订单号"+detailMessage.getOrderId()
								+ "，异常描述：" + detailMessage.getMessage());
						//订单同步失败
						originOrderService.updateDeliveryStatusfailure(detailMessage.getOrderId(),
								PlatConstants.ORDER_SOURCE_AM,detailMessage.getMessage());
					}
				}
			}
		}
	}

}
